import React, { useState, useEffect } from 'react';
import AutoCompleteInput from '@/rcomponents/autoCompleteInput';
import AviaMaintainStore from './aviaMaintainStore';

export default function AirportCompleter({ placeholder, onComplete }) {
  const [completer, setCompleter] = useState({
    airportSuggests: [], // value text
  });
  const aviaMtStore = AviaMaintainStore.useStore();
  useEffect(() => {
    let didCancel = false;
    async function fetchAirports() {
      const airports = await aviaMtStore.getAirports();
      if (!didCancel) {
        setCompleter({
          ...completer,
          airportSuggests: airports.map((arp) => ({
            value: arp.A_IATA_CODE,
            text: arp.A_Airport_Name,
          })),
        });
      }
    }
    fetchAirports();
    return () => {
      didCancel = true;
    };
  }, []);
  return (
    <AutoCompleteInput
      data={completer.airportSuggests}
      placeholder={placeholder}
      textExtractor={(airport) => `${airport.text} (${airport.value})`}
      onComplete={onComplete}
      flatListProps={{ listKey: 'airport' }}
    />
  );
}
